<template>
  <el-container class="Detail-Container">
    <el-aside class="Aside-Content" :width="!isMobile ? '13rem' : '100%'">
      <el-card shadow="hover" class="MusicScoreCard">
        <div class="musicScore-detail">
          <h1 class="musicScore-title">
            《{{ musicScore.info.music_score_title }}》
          </h1>
          <span
            v-if="
              musicScore.info.paid_product &&
                userInfo.id != musicScore.info.creator_id &&
                !isBuy
            "
            >该曲谱共
            {{ musicScore.referenceds_count }}
            页，非付费情况下只能查看一页或半页。购买付费服务可完整查看全部内容。如有疑问请联系管理员。</span
          >
          <span v-else-if="userInfo.id == musicScore.info.creator_id"
            >作者可阅览下载</span
          >
          <span v-else-if="isBuy" class="paid-content">该乐谱已被购买</span>

          <span v-else
            >该曲谱为免费乐谱共 {{ musicScore.referenceds_count }} 页</span
          >

          <div class="musicScoreList">
            <img
              v-for="(m, index) in musicScore.referenceds"
              :key="index"
              :class="
                musicScore.info.paid_product &&
                musicScore.referenceds.length == 1 &&
                userInfo.id != musicScore.info.creator_id
                  ? 'ShowHalf'
                  : ''
              "
              :src="m"
            />
          </div>
        </div>
      </el-card>
      <el-card class="optionContent" v-if="!isMobile" shadow="never">
        <div class="options">
          <!-- <div class="creatorname">来自:{{ musicScore.info.creator_name }}</div> -->
          <a class="icon thumb" :underline="false" @click="toggleLike">
            <img v-if="!isLiked" src="@/assets/img/svg/like.svg" />
            <img v-else src="@/assets/img/svg/like-active.svg" />
            {{ musicScore.info.like_count }}
          </a>
          <el-link
            :underline="false"
            @click="openCommentList"
            type="info"
            class="icon"
            ><img src="@/assets/img/svg/comment.svg" />
            {{ musicScore.info.comment_count }} 条评论</el-link
          >
          <el-link
            @click="shareMusicScore"
            :underline="false"
            type="info"
            class="icon"
          >
            <img src="@/assets/img/svg/share.svg" /> 分享
          </el-link>
        </div>

        <el-collapse-transition>
          <CommentList
            class="CommentList"
            v-if="isCommentOpen"
            :commentList="commentList"
            :page="page"
            :musicScore="musicScore.info"
            :count="count"
          />
        </el-collapse-transition>
      </el-card>

      <el-card class="Info-Content" v-else style="margin-top:0.6rem">
        <div class="musicScore-description">
          <!-- <h1 class="title">曲谱介绍</h1> -->
          <img
            :src="
              musicScore.info.img_url ? musicScore.info.img_url : defaultImg
            "
          />

          <!-- <h4 class="crearto">描述</h4> -->
          <span class="desc-content">{{ musicScore.content }}</span>
          <!-- <h1 :underline="false" type="danger" class="title">下载地址</h1> -->
          <span class="downloadAddress">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              width="14px"
              style="color:#b4b4b4;"
              focusable="false"
              aria-hidden="true"
            >
              <path
                fill-rule="evenodd"
                clip-rule="evenodd"
                d="M17.8395 8.05827C17.1837 5.16226 14.5944 3 11.5 3C7.91015 3 5 5.91015 5 9.5C5 10.0204 5.06115 10.5264 5.17665 11.0114C2.84229 11.1772 1 13.1234 1 15.5C1 17.9853 3.01469 20 5.49995 20H17C20.3137 20 23 17.3137 23 14C23 10.9712 20.7558 8.46659 17.8395 8.05827ZM11.6799 17.7333C11.8653 17.8878 12.1347 17.8878 12.3201 17.7333L17.4695 13.4421C17.6492 13.2924 17.5433 13 17.3095 13H14V9.5C14 9.22386 13.7761 9 13.5 9H10.5C10.2239 9 10 9.22386 10 9.5V13H6.69051C6.45669 13 6.35084 13.2924 6.53047 13.4421L11.6799 17.7333Z"
                fill="currentColor"
              ></path>
            </svg>
            <a
              style="color:#b4b4b4;"
              @click="downloadMusicScore"
              :underline="false"
              >下载乐谱</a
            >
          </span>

          <div class="taglist">
            <!-- <h1 class="title">标签</h1> -->

            <el-link
              :underline="false"
              class="tag"
              v-for="t in tagList"
              :key="t.id"
              >{{ t.tag_name }}</el-link
            >
          </div>
        </div>
      </el-card>
    </el-aside>
    <el-main class="Info-Container" v-if="!isMobile">
      <el-card class="Info-Content">
        <div class="musicScore-description">
          <!-- <h1 class="title">曲谱介绍</h1>
          <el-divider></el-divider> -->
          <img
            :src="
              musicScore.info.img_url ? musicScore.info.img_url : defaultImg
            "
          />
          <h5 class="creator">发布者：{{ musicScore.info.creator_name }}</h5>
          <!-- <h4 class="desc">描述:</h4> -->
          <span class="desc-content">{{ musicScore.content }}</span>
          <!-- <h1 :underline="false" type="danger" class="title">下载地址666天天网络错误</h1> -->

          <span
            class="downloadAddress"
            v-if="
              isBuy ||
                userInfo.id == musicScore.info.creator_id ||
                !musicScore.info.paid_product
            "
          >
            <svg
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              width="14px"
              style="color:#b4b4b4;"
              focusable="false"
              aria-hidden="true"
            >
              <path
                fill-rule="evenodd"
                clip-rule="evenodd"
                d="M17.8395 8.05827C17.1837 5.16226 14.5944 3 11.5 3C7.91015 3 5 5.91015 5 9.5C5 10.0204 5.06115 10.5264 5.17665 11.0114C2.84229 11.1772 1 13.1234 1 15.5C1 17.9853 3.01469 20 5.49995 20H17C20.3137 20 23 17.3137 23 14C23 10.9712 20.7558 8.46659 17.8395 8.05827ZM11.6799 17.7333C11.8653 17.8878 12.1347 17.8878 12.3201 17.7333L17.4695 13.4421C17.6492 13.2924 17.5433 13 17.3095 13H14V9.5C14 9.22386 13.7761 9 13.5 9H10.5C10.2239 9 10 9.22386 10 9.5V13H6.69051C6.45669 13 6.35084 13.2924 6.53047 13.4421L11.6799 17.7333Z"
                fill="currentColor"
              ></path>
            </svg>
            <a
              style="color:#b4b4b4;cursor:pointer;"
              @click="downloadMusicScore"
              :underline="false"
              >下载乐谱</a
            >
          </span>
          <span class="downloadAddress" v-else
            ><img src="@/assets/img/svg/buy.svg" />
            <el-link @click="BuyMusicScore" :underline="false"
              >购买乐谱</el-link
            >
          </span>
          <div class="taglist">
            <el-link
              :underline="false"
              class="tag"
              v-for="t in tagList"
              :key="t.id"
              >{{ t.tag_name }}</el-link
            >
          </div>
        </div>
      </el-card>
    </el-main>
    <el-footer class="Info-Container" v-else>
      <el-card class="optionContent" shadow="never">
        <div class="options">
          <!-- <div class="creatorname">来自:{{ musicScore.info.creator_name }}</div> -->
          <el-link class="thumb" :underline="false" @click="toggleLike">
            <img v-if="!isLiked" src="@/assets/img/svg/like.svg" />
            <img v-else src="@/assets/img/svg/like-active.svg" />
            {{ musicScore.info.like_count }}
          </el-link>
          <el-link
            :underline="false"
            @click="openCommentList"
            type="info"
            class="icon"
            ><img src="@/assets/img/svg/comment.svg" />
            {{ musicScore.info.comment_count }} 条评论</el-link
          >
          <el-link
            @click="shareMusicScore"
            :underline="false"
            type="info"
            class="icon"
          >
            <img src="@/assets/img/svg/share.svg" /> 分享
          </el-link>
        </div>

        <el-collapse-transition>
          <CommentList
            class="CommentList"
            v-if="isCommentOpen"
            :commentList="commentList"
            :page="page"
            :musicScore="musicScore.info"
            :count="count"
          />
        </el-collapse-transition>
      </el-card>
    </el-footer>
  </el-container>
</template>

<script>
import CommentList from '@/components/Comment/CommentList'
import Tags from '@/components/Article/Tags'
import { copyToClipboard } from '@/utils/tools'
import defaultImg from '@/assets/img/defaultImg.jpg'
import {
  downLoadFile,
  downloadBatchFile,
  downLoadFileOrFolder
} from '@/api/cos'
import JSZip from 'jszip'

export default {
  name: 'MusicScoreDetail',
  props: {},
  components: {
    CommentList,
    Tags
  },
  data() {
    return {
      musicScoreId: {},
      musicScore: {},
      isLiked: false,
      page: 1,
      limit: 3,
      count: 0,
      isReload: false,
      isCommentOpen: false,
      tagList: [],
      commentList: [],
      defaultImg: defaultImg,
      isBuy: false,
      downloadLink: null
    }
  },
  computed: {
    isMobile() {
      return this.$data.isMobile
    },
    userInfo() {
      return this.$store.state.user.userInfo
    }
  },
  watch: {
    '$route.params.id': {
      handler(val) {
        window.location.reload()

        // 或者使用路由跳转到当前页面
        this.$router.replace(this.$router.currentRoute)
      }
    }
  },
  created() {},
  mounted() {
    // 获取乐谱
    this.$nextTick(() => {
      this.readMusicScore()
    })
  },
  methods: {
    // 购买乐谱
    async BuyMusicScore() {
      this.$confirm('是否购买该乐谱?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let formData = new FormData()
          formData.append('music_score_id', this.musicScore.info.id)
          const res = await this.$API.musicScore.BuyMusicScoreByCoin(formData)
          if (res.status == 200) {
            this.isBuy = true
            this.readMusicScore()
          } else if (res.status == 402) {
            this.$message.warning(res.msg)
          }
        })
        .catch(() => {})
    },
    // 获取当前用户购买乐谱状态
    async getPaidStatus() {
      // 整理数据
      const { musicScore, userInfo } = this
      const res = await this.$API.musicScore.ReviewUserMusicScorePaidStatus(
        userInfo.id,
        musicScore.info.id
      )
      console.log('res', res)
      if (res.status == 200) {
        this.isBuy = res.data ? true : false
      }
    },
    // 获取文章
    async getMusicScore() {
      // 通过路由获取id
      this.musicScoreId = this.$route.params.id
      const res = await this.$API.musicScore.RefreshMusicScore(
        this.musicScoreId
      )
      if (res.status == 200) {
        this.musicScore = res.data
        this.isBuy = this.musicScore.paid_product
        this.getMusicScoreThumbStatus()
        this.getAllTags()
        this.getPaidStatus()
      } else {
        this.$message.warning('你所阅读的文章已被删除')
        this.$router.push('/musicScore')
      }
    },
    // 第一次进入页面阅读文章
    async readMusicScore() {
      // 通过路由获取id
      this.musicScoreId = this.$route.params.id
      const res = await this.$API.musicScore.getMusicScoreById(
        this.musicScoreId
      )
      console.log(res)
      if (res.status == 200) {
        this.musicScore = res.data
        this.getMusicScoreThumbStatus()
        this.getAllTags()
        // 获取当前用户是否购买乐谱
        this.getPaidStatus()
      } else {
        this.$message.warning('你所阅读的文章已被删除')
        this.$router.push('/musicScore')
      }
    },
    // 获取该文章所有tag
    async getAllTags() {
      const res = await this.$API.tags.getMusicScoreTags(
        this.musicScore.info.id
      )
      if (res.status == 200) {
        this.tagList = res.data
      }
    },
    // 点赞按钮
    async toggleLike() {
      let datas = this.$qs.stringify({
        music_score_id: this.musicScore.info.id
      })
      const res = await this.$API.musicScore.MusicScoreThumb(datas)
      if (res.status == 200) {
        this.isLiked = !this.isLiked
        // 重新获得文章数据
        this.getMusicScore()
      }
    },
    // 获取用户点赞状态
    async getMusicScoreThumbStatus() {
      console.log(this.musicScore.info.id)
      const res = await this.$API.musicScore.getMusicScoreThumbStatus(
        this.musicScore.info.id
      )
      if (res.status == 200) {
        this.isLiked = res.data ? true : false
      } else {
        this.isLiked = false
      }
    },
    // 打开评论列表
    async openCommentList() {
      const { musicScore, limit, page } = this
      console.log('isReload', this.isReload)
      if (this.isCommentOpen) return (this.isCommentOpen = !this.isCommentOpen)
      // 获取评论列表
      // this.$store.dispatch("musicScore/getCurrentCommentList", { musicScore: musicScore.info, limit, page })
      const res = await this.$API.musicScore.getCommentList(
        musicScore.info.id,
        limit,
        page
      )
      console.log('res', res)
      if (res.status == 200) {
        this.commentList = res.data.payload
        this.count = res.data.count

        // 判断是否为更新数据
        this.isCommentOpen = !this.isCommentOpen
      } else if (res.status == 422) {
        this.isCommentOpen = !this.isCommentOpen
        this.$bus.$emit('ReloadCommentList')
      }
    },
    // 分享文章
    shareMusicScore() {
      const currentUrl = window.location.href
      copyToClipboard(currentUrl) // 调用复制链接到剪贴板的方法
      alert('当前页面链接已复制到剪贴板')
    },
    // 下载乐谱
    async downloadMusicScore() {
      if (
        this.musicScore.info.paid_product &&
        this.userInfo.id != this.musicScore.info.creator_id &&
        !this.isBuy
      )
        return this.$message.warning('付费后下载')
      // cos下载乐谱
      this.$confirm('是否下载该乐谱?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { musicScore } = this
          // 移除之前创建的 <a> 标签
          if (this.downloadLink) {
            document.body.removeChild(this.downloadLink)
            this.downloadLink = null
          }
          let completedCount = 0 // 已完成下载的文件数量

          const response = await downLoadFileOrFolder(
            'musicScore/' + musicScore.info.file_code
          )
          let zip = new JSZip()
          console.log(response)
          for (let i = 0; i < response.length; i++) {
            if (response) {
              let fileData = response[i].data.Body
              zip.file(response[i].key, fileData) // 使用文件名作为参数
              completedCount++

              // 更新下载进度
              this.$message({
                type: 'info',
                message: `已下载 ${completedCount} / ${response.length} 个文件`
              })
            }
          }

          // 生成 ZIP 压缩包
          zip
            .generateAsync({ type: 'blob' })
            .then(blob => {
              // 创建新的 <a> 标签用于触发下载
              this.downloadLink = document.createElement('a')
              this.downloadLink.href = URL.createObjectURL(blob)
              this.downloadLink.download = decodeURIComponent(
                musicScore.info.file_code + '.zip'
              ) // 设置下载文件的名称
              this.downloadLink.style.display = 'none'

              // 将 <a> 标签添加到 DOM 中
              document.body.appendChild(this.downloadLink)

              // 触发下载
              this.downloadLink.click()

              this.loading = false

              this.$message({
                type: 'success',
                message: '下载成功!'
              })
            })
            .catch(err => {
              console.log(err)
              this.$message({
                type: 'warning',
                message: '下载失败'
              })
              this.loading = false
            })
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'warning',
            message: '下载失败'
          })
          this.loading = false
        })

      // 本地下载乐谱
      // const datas = {
      //   url: this.musicScore.referenceds[0]
      // }
      // const response = await this.$API.musicScore.downLoad(this.$qs.stringify(datas))
      // console.log(response)
      // if (response) {
      //   // 处理url
      //   const url = window.URL.createObjectURL(new Blob([response]));
      //   const link = document.createElement('a');
      //   link.href = url;
      //   // 指定格式
      //   link.setAttribute('download', this.musicScore.info.music_score_title + ".png");  // 设置文件名
      //   // 将a标签添加到页面中并模拟点击
      //   document.body.appendChild(link);
      //   link.click();
      //   // 清理临时的URL对象
      //   window.URL.revokeObjectURL(url);
      //   this.$message.success("下载成功")
      // }
    }
  }
}
</script>

<style scoped src="@/assets/style/modules/musicScore/musicScoreDetail.css">
</style>
